package com.study.talk.ui.app.login.fragment

import android.app.Application
import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.study.common.DateUtil
import com.study.talk.ui.app.base.BaseViewModel
import com.study.talk.netty.NettyClient
import com.study.talk.netty.message.request.LoginRequest
import com.study.talk.utils.extras.useless
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject

@HiltViewModel
class LoginFragmentViewModel @Inject constructor(application: Application) : BaseViewModel(application){

    val username = MutableLiveData("")
    val password = MutableLiveData("")

    fun autoLogin() : LoginRequest? {
        val sharedPreferences = app.getSharedPreferences("account", Context.MODE_PRIVATE)
        val username = sharedPreferences.getString("username", "").toString()
        val password = sharedPreferences.getString("password", "").toString()
        return if (username.isNotEmpty() && password.isNotEmpty()) {
            LoginRequest(
                DateUtil.currentTime(), username, password, false, true, null
            )
        }else{
            null
        }
    }

    fun check() : Boolean{
        if (username.value?.useless(app,"请输入用户名") == true) return false
        if (password.value?.useless(app,"请输入密码") == true) return false
        return true
    }

    fun submit(){
        val username = username.value?.trim()
        val password = password.value?.trim()
        val loginRequest = LoginRequest(
            DateUtil.currentTime(), username, password, true, true, null
        )
        NettyClient.sendMessage(loginRequest)
    }
}